import Vue from 'cheways-vue'

//存入模版信息
var pageConfig = {
	'main': {
		url: './main.html',
		id: 'main',
		styles: {
			'popGesture': 'none'
		},
		waiting: {
			autoShow: false,
		}
	},
	'find-password': {
		url: '../../build/find-password/step1.html',
		id: 'find-password-step1',
		styles: {
			'popGesture': 'none',
			top: 0,
		}
	},
	'register': {
		url: '../../build/register/register.html',
		id: 'register',
		styles: {
			'popGesture': 'none',
			top: 0,
		}
	},
	'device-list': {
		url: '../../build/device-list/device-list.html',
		id: 'device-list',
		styles: {
			'popGesture': 'none'
		}
	}
};
window.vm = new Vue({
	el: '#app',
	data: {
		showLogin: true,
		userName: '',
		password: '',
		type: 3, //3表示普通用户，2表示管理员
	},
	mounted: function() {
		var _self = this;
		window.addEventListener('pagebeforeshow', this.pageBeforeShow, false);

		mui.init({});
		mui.plusReady(function() {
			//手动关闭启动页
			plus.navigator.closeSplashscreen();
		});
		//一秒内连续点击两次，退出应用，仅安卓有效；
		mui.back = this._back;
		window.addEventListener('fleetLogin', function(event) {
			_self.fleetLogin(event.detail);
		});
		window.addEventListener('lastAutoLogin', function(event) {
			var ll = JSON.parse(localStorage.lastLogin)
			_self.autoLogin(ll.name, ll.pwd);
		});
		window.addEventListener('autoLogin', function(event) {
			_self.autoLogin(event.detail.mobile, event.detail.password);
		});
	},
	computed: {
		canLogin: function() {
			var result = this.userName.trim().length > 0 && (this.password.length >= 6 || (this.type == 2 && this.password.length >= 1));
			console.log(result);
			return result;
		},
	},
	methods: {
		autoLogin: function(name, pwd) {
			this.userName = name;
			this.password = pwd;
			this.login();
		},
		pageBeforeShow: function() {
			this.userName = JSON.parse(localStorage.lastLogin || '{}').name || '';
			localStorage.removeItem('userData');
		},
		login: function() {
			//发送数据start
			if(localStorage.appId == 'com.birdsh.cheways.dys') {
				logeye.emit({
					events: 'dys_login_login'
				})
			}
			if(localStorage.appId == 'com.birdsh.cheways.lf') {
				logeye.emit({
					events: 'lf_login_login'
				})
			}
			//发送数据end
			var _self = this,
				userName = _self.userName.trim(),
				password = _self.password.trim(),
				cid = "";

			if(!userName || !password) {
				mui.toast('用户名或密码不能为空！');
				return;
			}
			localStorage.setItem('chewaysMobile','');
			//若是手机号，传上次的设备号给后端（用于后端确定token）
			if(app.Reg.IS_MOBILE.test(userName)) {
				cid = localStorage["bind:" + userName] || '';
				localStorage.setItem('chewaysMobile',userName);
			}
			var loginData = {
				name: _self.userName,
				pwd: _self.password,
				type: _self.type,
				cid: cid,
				packageName: localStorage.appId,
			};
			app.ajax({
				url: app.api['login'],
				data: loginData,
				showWaiting: '请稍等...',
				closeWaiting: false,
				success: function(data,message) {
					app.closeWaiting();
					if (data.prompt == 1) {  //设备号已激活但手机号未注册过
						mui.confirm(message, localStorage.appName, ['去注册', '稍后再说'], function(e) {
							if (e.index == 0) {
								mui.openWindow({url: "../register/register.html?mobile="+(data.clink||'')});
							} else {
								continueLogin();
							}
						})
					} else {
						continueLogin();
					}
					
					function continueLogin() {
						_self.logins = data;
						localStorage.lastLogin = JSON.stringify(loginData);
						_self.password = '';
						
						if(!data.device) {  //管理员
							app.closeWaiting();
							localStorage.adminToken = data['access_token'];
							vm.openWindow(pageConfig['device-list']);
							return;
						}
						
						if (data.contents == '4') {
							localStorage.activateToken = data['access_token'];
							app.closeWaiting();
							mui.alert('您的设备未激活', '', '去激活', function(e) {
								if (e.index == 0)
									vm.openWindow({url: '../activate/activate.html', styles: {top: 0}});
							});
						} else {
							_self.userLogin(data);
						}
					}
				},
				error: function() {
					app.closeWaiting();
				}
			});

		},
		fleetLogin: function(item) {
			localStorage.setItem('token', localStorage.adminToken);
			localStorage.setItem('user', new User(item.cid, "admin", item.clink));
			app.ajax({
				url: app.api.decideGetPush,
				data: {
					cid: item.cid
				},
				success: function() {}
			});
			mui.openWindow(pageConfig['main']);
		},
		findPassword: function() {
			//发送数据start
			if(localStorage.appId == 'com.birdsh.cheways.dys') {
				logeye.emit({
					events: 'dys_login_findPassword'
				})
			}
			if(localStorage.appId == 'com.birdsh.cheways.lf') {
				logeye.emit({
					events: 'lf_login_findPassword'
				})
			}
			//发送数据end			
			vm.openWindow(pageConfig['find-password']);
		},
		switchToggle1: function() {
			this.type = 3;
			var p = document.getElementsByClassName('personal-login');
			var m = document.getElementsByClassName('manager-login');
			p[0].style.backgroundColor = 'rgb(209,148,23)';
			m[0].style.backgroundColor = '#fff';
			p[0].style.color = '#fff';
			m[0].style.color = 'rgb(209,148,23)';
		},
		switchToggle2: function() {
			this.type = 2;
			var p = document.getElementsByClassName('personal-login');
			var m = document.getElementsByClassName('manager-login');
			p[0].style.backgroundColor = '#fff';
			m[0].style.backgroundColor = 'rgb(209,148,23)';
			p[0].style.color = 'rgb(209,148,23)';
			m[0].style.color = '#fff';
		},
		register: function() {
			vm.openWindow(pageConfig['register']);
		},
		userLogin: function(data) {
			//刷新手机号绑定的最新登录设备，用于手机号登录
			localStorage.setItem("bind:" + data.ctel, data.device[0]);
			localStorage.token = data['access_token'];
			var u = new User(data.device[0], 'normal', data.clink);
			u.ctel = data.ctel;
			localStorage.user = JSON.stringify(u);
			mui.openWindow(pageConfig['main']);
		},
		_back: function() {
			var self = this;
			if(!self.firstTime) {
				self.firstTime = new Date().getTime();
				plus.nativeUI.toast("再按一次退出应用");
				setTimeout(function() {
					self.firstTime = null;
				}, 1000);
			} else {
				if(new Date().getTime() - self.firstTime < 1000) {
					var main = plus.android.runtimeMainActivity();
					main.moveTaskToBack(false);
				}
			}
		}
	}
});